﻿using GC_FFW.BusinessEntities.Abstractions.Interfaces.Forecast;
using GC_FFW.BusinessEntities.Forecast.Xml;
using GC_FFW.ForecastWriter.Abstractions.Adapters;
using GC_FFW.ForecastWriter.Abstractions.Interfaces.Helpers;
using GC_FFW.ForecastWriter.Common;
using System.Collections.Generic;
using System.Linq;

namespace GC_FFW.ForecastWriter.Adapters.TeamMatch.AwayTeamLastResults
{
	public class FirstMatchProposalAdapter : ProposalBaseAdapter
	{
		#region Constructors

		public FirstMatchProposalAdapter(IForecastData forecastData, Conditions conditions,
			IStringManager stringManager, IRandomizer randomizer)
			: base(forecastData, conditions, stringManager, randomizer) { }

		#endregion

		#region Overrides

		public override string GetText()
		{
			if (ForecastData.AwayTeam == null || ForecastData.AwayTeam.LastMatches == null || !ForecastData.AwayTeam.LastMatches.Any())
				return string.Empty;

			var result = string.Empty;

			var match = ForecastData.AwayTeam.GetMatch(1);
			if (match == null) return result;

			var goalDiff = match.TeamGoalsCount(ForecastData.AwayTeam.Name) -
				match.OpponentTeamGoalsCount(ForecastData.AwayTeam.Name);

			var proposal = GetProposal(Conditions.GetCondition(
				match.IsTeamWin(ForecastData.AwayTeam.Name) && goalDiff < 2
					? 1
					: match.IsTeamWin(ForecastData.AwayTeam.Name) && goalDiff >= 2
						? 2
						: !match.HasWinner
							? 3
							: 4));
			if (proposal == null) return string.Empty;

			result = proposal.Text ?? string.Empty;
			if (proposal.KeywordList == null || !proposal.KeywordList.Any()) return result;

			var dictionary = new Dictionary<string, string>();
			foreach (var keyword in proposal.KeywordList)
			{
				switch (keyword)
				{
					case Constants.AWAY_TEAM_NAME_KEYWORD:

						dictionary.Add(
							Constants.AWAY_TEAM_NAME_KEYWORD,
							ForecastData.AwayTeam.Name ?? string.Empty);

						break;

					case Constants.OPPONENT_NAME_KEYWORD:

						dictionary.Add(
							Constants.OPPONENT_NAME_KEYWORD,
							match.OpponentTeamName(ForecastData.AwayTeam.Name));

						break;

					case Constants.MATCH_RESULT_KEYWORD:

						dictionary.Add(
							Constants.MATCH_RESULT_KEYWORD,
							match.MatchResult);

						break;
				}
			}

			result = StringManager.ReplaceKeywords(result, dictionary);

			return result;
		}

		#endregion
	}
}
